package com.hzqy.commons.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hzqy.persistence.dao.commons.CommonsDao;
import com.hzqy.web.vo.SysConfigVo;

public class SystemConfigUtils {
	private static final Log LOG = LogFactory.getLog(SystemConfigUtils.class);
	private static HashMap<String,String> systemConfigHash = new HashMap<String,String>();
	private static CommonsDao commonsDao;
	private static long maxCacheTime = 10*60*1000; //缓存超过5分钟，就去数据库中查询一次
	private static long cacheBeginTime = System.currentTimeMillis(); //缓存开始时间
	
	private SystemConfigUtils(){}
	public static boolean init(CommonsDao commonsDao) {
		SystemConfigUtils.commonsDao = commonsDao;
		return setSysConfig(commonsDao.selectSystemConfig());
	}
	
	/**
	 * 需要从SessionKey.SESSION_SYSTEM_CONFIG.private_net_url.getKey()获取key<br/>
	 * 注意优先级问题，默认是带私网IP优先级最高，不带私网IP优先级低
	 * @param key
	 * @return
	 */
	public static String getSysConfig(String key) {
		long nowTime = System.currentTimeMillis();
		if(nowTime-cacheBeginTime>maxCacheTime) { //判断缓存是否已经超过maxCacheTime5分钟了，超过则更新时间和从数据库中查询缓存内容
			cacheBeginTime = nowTime;
			setSysConfig(commonsDao.selectSystemConfig());
		}
		String value = null;
		try {
			String combineKey = "";
			Enumeration<NetworkInterface> netInterfaces = null;
			netInterfaces = NetworkInterface.getNetworkInterfaces();

		    while (netInterfaces.hasMoreElements()) {
		    	NetworkInterface ni = netInterfaces.nextElement();
		        Enumeration<InetAddress> ips = ni.getInetAddresses();
				int i =0;
		        while (ips.hasMoreElements()) {
		        	i++;
		        	//combineKey = key+"_"+ips.nextElement().getHostAddress(); //当有多台服务器时，key不变，在key后加上_ip
		        	combineKey = key+"_"+"ip"+i; //当有多台服务器时，key不变，在key后加上_ip
		        	//LOG.debug("组合combineKey="+combineKey);
		            value = systemConfigHash.get(combineKey);
		            if(value != null)
		            	return value; //带私网IP优先级高
		        }
		    }
		} catch (Exception e) {
			LOG.error("获取服务器IP地址列表异常：",e);
		}
		return systemConfigHash.get(key);
	}
	
	public static boolean setSysConfig(List<SysConfigVo> sysConfigList) {
		for(int i = 0; i < sysConfigList.size(); i++) {
			String db_key = sysConfigList.get(i).getF_sc_key().trim();
			String db_value = sysConfigList.get(i).getF_sc_value();
			if(db_value!=null)
				db_value = db_value.trim();
			systemConfigHash.put(db_key, db_value);
			LOG.debug("系统配置(sys_config表)："+sysConfigList.get(i).getF_sc_desc()+"="+db_key+"="+db_value);
		}
		return true;
	}
}
